<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="referrer" content="no-referrer">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>网络收藏夹|搜索</title>
    <link rel="icon" href="favicon.ico" type="image/x-icon" />
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="layui/css/layui.css">
    <style type="text/css">


			.main {
				margin: 0 auto;
				width: 90%;
				text-align: center;
				max-width: 654px;
			}

			.logo {
				margin-top: 100px;
				margin-bottom: 40px;
				display: flex;
                line-height: 32px;
                justify-content: center;
                cursor: pointer;
			}

			.search-form {
				border: 1px solid #009688;
				border-radius: 4px;
				height: 40px;
				position: relative;
			}

			.search-form button {
			    position: absolute;
                right: -1px;
                top: -1px;
				height: 42px;
                border-radius: 0 4px 4px 0;
                line-height: 42px;
			}

			.search-close {
			    position: absolute;
                top: 8px;
                right: 90px;
                cursor: pointer;
                display: none;
                font-size: 22px;
                color: #009688;
			}

			.search-form input {
				height: 100%;
				border: none;
				padding-right: 112px;
			}

			.search-items {
				position: absolute;
				width: calc(100% - 84px);
				top: 44px;
				left: 0;
				border: 1px solid #009688;
				border-radius: 4px;
				background: #FFFFFF;
				display: none;
				z-index: 999;
			}

			.search-items li {
				line-height: 32px;
				text-align: left;
				cursor: pointer;
				position: relative;
				padding-left: 10px;
                padding-right: 30px;
			}

			.search-items li.hover-in {
				color: #009688;
			}

			.search-items li .history-close {
                font-size: 14px;
                position: absolute;
                top: 0;
                right: 12px;
                font-weight: bold;
            }

			.search-type {
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				margin-top: 30px;
				margin-bottom: 30px;
				max-height: 300px;
                overflow: auto;
			}

			.search-type li {
				display: flex;
				flex-direction: row;
				width: 25%;
				cursor: pointer;
				padding: 10px;
				margin-bottom: 10px;
				border-radius: 4px;
				box-sizing: border-box;
				position: relative;
				align-items: center;
			}

			.search-type li:hover {
				background-color: #f5f5f5;
			}

			.search-type li.search-type-selected {
				background-color: #f5f7fa;
			}

			.search-type li img {
			    flex: 0 0 auto;
				width: 20px;
				height: 20px;
				margin-right: 6px;
				border: none;
			}

			.search-type li .layui-icon {
			    position: absolute;
                right: 8px;
                top: 12px;
                display: none;
			}

			.search-type li:hover .layui-icon {
			    display: block;
			}

			.search-type li span {
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
				word-break: break-all;
			}

			.home-icon {
				width: 30px;
				height: 30px;
				margin-top: 16px;
				margin-left: 20px;
				cursor: pointer;
			}

			.header {
			    position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 60px;
                box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
                display: flex;
                justify-content: space-between;
			}

			.center {
			    position: fixed;
                width: 100%;
                top: 60px;
                bottom: 44px;
                overflow: auto;
			}

			.footer {
			    position: fixed;
                bottom: 0;
                width: 100%;
                text-align: center;
                height: 44px;
                line-height: 44px;
			}

			#logout {
                margin-top: 20px;
                margin-right: 20px;
			}

			.tips-icon {
                margin-top: 8px;
                display: inline-block;
                font-size: 18px;
                color: #5e6d82;
                cursor: pointer;
            }
		</style>
</head>
<body>
<div class="header">
    <a href="index.html"><img class="home-icon" src="images/home.svg" alt=""></a>
    <button class="layui-btn layui-btn-xs" type="button" id="logout">退出</button>
</div>
<div class="center" id="center">
    <div class="main">
        <div class="logo" onclick="window.location.reload();">
            <i class="layui-icon layui-icon-search" style="font-size: 28px;color: #009688;margin-right: 6px;"></i>
            <h1 style="color: #009688;">聚合搜索</h1>
        </div>
        <div class="search-form">
            <input class="layui-input" type="text" id="search_content" value="" />
            <button class="layui-btn layui-btn-lg" type="button" id="search_btn">搜索</button>
            <ul class="search-items layui-anim layui-anim-fadein"></ul>
            <i class="layui-icon layui-icon-close-fill search-close layui-anim layui-anim-fadein" id="search_close" style="display:none;"></i>
        </div>
        <ul class="search-type" id="searchTypeList"></ul>
    </div>
</div>
<div class="footer">
    © 2020 网络收藏夹 || 网络收藏夹版权所有
</div>
<!-- 添加搜索引擎表单 -->
<form class="layui-form" action="" id="searchTypeFrom" lay-filter="searchTypeFrom" style="display: none;padding: 10px">
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="text" name="name" required lay-verify="required|name" placeholder="请输入引擎名称" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">地址</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="text" name="url" required lay-verify="required|url" placeholder="请输入引擎地址" autocomplete="off"
                   class="layui-input">
        </div>
        <i class="layui-icon layui-icon-tips tips-icon" lay-title="示例：https://www.bing.com/search?q=hello"></i>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="addSearchType">立即提交</button>
            <button type="button" class="layui-btn layui-btn-primary" id="cancelAddSearchType">取消</button>
        </div>
    </div>
</form>
<script src="layui/jquery-3.1.1.min.js" type="text/javascript" charset="utf-8"></script>
<script src="layui/layui.js"></script>
<script type="text/javascript">
        layui.use(['layer', 'form', 'flow'], function(){
            var layer = layui.layer;
            var form = layui.form;
            var flow = layui.flow;

            var indexMap = new Map();// 弹出层索引容器

            // 点击空白关闭
            $(document).on("click", function(e) {
                var _conss = $('.search-form');//点击的容器范围
                if (!_conss.is(e.target) && _conss.has(e.target).length === 0) {
                    $(".search-items").hide();
                    $("#search_close").hide();
                }
            });

            // jQuery全局拦截器
            $(document).ajaxSuccess(function(event,xhr,options){
                var result = xhr.responseJSON;
                if(result != undefined && result.code == "401"){
                    window.location.href= "login.html";
                }
            });

            // 加载数据
            flow.load({
                elem: '#searchTypeList'
                ,scrollElem: '#searchTypeList'
                ,isLazyimg: true
                ,mb: 50
                ,end: ' '
                ,done: function(page, next){
                  var lis = [];
                  if(page == 1){
                    $.ajax({
                        type: "GET",
                        url: "search.json",
                        async: false,
                        dataType: "json",
                        success: function (data) {
                           $.each(data, function(i, item){
                                var html = '';
                                html += '<li class="search-type-li" data-search="' + item.url + '"><img src="images/web.svg" lay-src="' + item.icon + '"><span>' + item.name +
                                    '</span></li>';
                                lis.push(html);
                           });
                        }
                    });
                  }
                    $.ajax({
                        type: "GET",
                        url: "search/data",
                        data: {"pageNum": page,"pageSize": 20},
                        dataType: "json",
                        headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                        success: function (result) {
                            if(result.code == 0){
                                $.each(result.data.list, function(index, item) {
                                    var html = '';
                                    html += '<li class="search-type-li" data-id="' + item.id + '" data-search="' + item.url + '"><img src="images/web.svg" lay-src="' + item.icon + '"><span>' + item.name +
                                        '</span><i class="layui-icon layui-icon-close" onclick="deleteSearchType(event)"></i></li>';
                                    lis.push(html);
                                });
                                $("#addBtn").remove();
                                var addBtn = '<li id="addBtn" onclick="addSearchType()"><img src="images/add.svg"><span>添加搜索</span></li>';
                                lis.push(addBtn);
                                next(lis.join(''), page < result.data.pages);
                            }
                        }
                    });
                }
            });

            $(".layui-icon-tips").hover(function(){
                var that = $(this);
                layer.tips(that.attr("lay-title"), that, {tips: 3});
            },function(){
                layer.closeAll('tips');
            });

            $(document).on("keydown", function(event){
                if(event.ctrlKey && event.key === "f"){
                    $("#search_content").focus();
                    // 阻止默认浏览器动作(W3C)
                    var e = event;
                    if ( e && e.preventDefault )
                        e.preventDefault();
                    // IE中阻止函数器默认动作的方式
                    else
                        window.event.returnValue = false;
                    return false;
                }
            });

            // 根据数组的下标，删除该下标的元素
            Array.prototype.remove = function(val) {
                var index = this.indexOf(val);
                if (index > -1) {
                    this.splice(index, 1);
                }
            };

            // 登出
            $("#logout").click(function () {
                layer.confirm('确认退出系统吗？', function(index){
                    layer.close(index);

                    localStorage.clear();
                    window.location.href = "login.html";
                });
            });

            // 删除搜索引擎
			window.deleteSearchType = function(event){
			    event.stopPropagation();

			    layer.confirm('确认删除搜索引擎吗?', function(index){
                    layer.close(index);
                    layer.load();

                    var id = $(event.target).parent().attr("data-id");
                    $.ajax({
                        type: "GET",
                        url: "search/delete/" + id,
                        dataType: "json",
                        headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                        success: function (result) {
                            layer.closeAll('loading');
                            if (result.code == 0) {
                                window.location.reload();
                            } else {
                                layer.msg("删除失败", {icon: 5});
                            }
                        }
                    });
                });
			};

			// 添加搜索引擎
			window.addSearchType = function(){
			    var index = layer.open({
                    type: 1,
                    title: "添加搜索引擎",
                    area: '400px',
                    content: $('#searchTypeFrom')
                });
                indexMap.set('#searchTypeFrom',index);
                // 表单赋值
                form.val("searchTypeFrom", {
                    "name": ""
                    , "url": ""
                });
			};

			//监听提交
            form.on('submit(addSearchType)', function(data){
                layer.load();
                data.field.url = data.field.url.replace("=hello","");
                $.ajax({
                    type: "POST",
                    url: "search",
                    data: JSON.stringify(data.field),
                    contentType: 'application/json;charset=utf-8',
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        layer.closeAll('loading');
                        layer.close(indexMap.get('#searchTypeFrom'));
                        if (result.code == 0) {
                            window.location.reload();
                        } else {
                            layer.msg("添加失败", {icon: 5});
                        }
                    }
                });
                return false;
            });

            form.verify({
              name: function (value, item) {
                if(value.length>20){
                    return '最多输入20个字符';
                }
              }
            });

			$("#cancelAddSearchType").click(function () {
                layer.close(indexMap.get('#searchTypeFrom'));
            });

			// 搜索类型绑定点击事件
			$(document).on('click', '.search-type-li', function() {
				$(this).addClass('search-type-selected').siblings().removeClass('search-type-selected');
				if ($("#search_content").val().trim() !== "") $("#search_btn").trigger("click");
			});

			// 搜索项绑定hover事件
			$(document).on('mouseenter', '.search-items li', function() {
				$(this).addClass('hover-in');
			});

			$(document).on('mouseleave', '.search-items li', function() {
				$(this).removeClass('hover-in');
			});

			// 搜索项绑定点击事件
			$(document).on('click', '.search-items li', function() {
				$("#search_content").val($(this).text());
				$(this).parent().hide();
				$("#search_btn").trigger("click");
			});

			$(document).on('click', '.search-items li .history-close', function(event) {
                event.stopPropagation();

                $(this).parent().remove();
                if($(".search-items").children().length === 0) $(".search-items").hide();

                var text = $(this).parent().text();
                var search_history = JSON.parse(localStorage.getItem("search_history"));
                if(search_history.indexOf(text) >= 0) {
                    search_history.remove(text);
                    localStorage.setItem("search_history", JSON.stringify(search_history));
                }
            });

			$("#search_close").click(function() {
			    $("#search_content").val("");
			    $(".search-items").hide();
			    $(this).hide();
			});

			// 点击搜索按钮搜索
			$("#search_btn").click(function() {
				var content = $("#search_content").val().trim();
				if (content != "") {
					// 存入历史记录
					var search_history = JSON.parse(localStorage.getItem("search_history"));
					if (search_history == null || search_history.length >= 10) search_history = [];
					if (search_history.indexOf(content) < 0) search_history.push(content);
					localStorage.setItem("search_history", JSON.stringify(search_history));
					// 跳转页面
					var search_url = $(".search-type .search-type-li.search-type-selected").attr("data-search");
					search_url = typeof search_url === "undefined" ? "https://www.baidu.com/s?wd=" : search_url;
					openUrl(search_url + content);
				} else {
					window.location.reload();
				}
			});

			$("#search_content").keyup(function(event) {
				if (event.key === "Enter") { // 回车搜索，隐藏搜索项
					$("#search_btn").trigger("click");
					$(".search-items").hide();
				} else if (event.key === "ArrowUp") {
					var hover_in = typeof $(".search-items li.hover-in")[0] === "undefined" ? $(".search-items li:last")[0] : $(
						".search-items li.hover-in").prev()[0];
					if (typeof hover_in !== "undefined") {
						$(hover_in).addClass('hover-in').siblings().removeClass('hover-in');
						$(this).val(hover_in.innerText);
					}
				} else if (event.key === "ArrowDown") {
					var hover_in = typeof $(".search-items li.hover-in")[0] === "undefined" ? $(".search-items li:first")[0] : $(
						".search-items li.hover-in").next()[0];
					if (typeof hover_in !== "undefined") {
						$(hover_in).addClass('hover-in').siblings().removeClass('hover-in');
						$(this).val(hover_in.innerText);
					}
				}
			}).bind("input propertychange", function() { // 输入框输入值，查询百度词条
				var keyword = $(this).val().trim();
				if (keyword !== "") {
					$.ajax({
						url: "https://www.baidu.com/su?wd=" + keyword,
						type: "GET",
						dataType: "jsonp", //指定服务器返回的数据类型
						jsonp: "cb",
                        success: function(data) {
							var html = '';
							$.each(data.s, function(index, item) {
								html += '<li>' + item + '</li>';
							});
							if (html != "") $(".search-items").empty().append(html).show();
						}
					});
				}
			}).focus(function() { // 输入框聚焦，显示历史搜索
		        $("#search_close").show();
		        var html = '';
				var search_history = JSON.parse(localStorage.getItem("search_history"));
				$.each(search_history, function(index, item) {
					html = '<li>' + item + '<i class="layui-icon layui-icon-close history-close"></i></li>' + html;
				});
				if (html !== "") $(".search-items").empty().append(html).show();
			});

			window.openUrl = function(url) {
				if (url.indexOf("https://") == 0 || url.indexOf("http://") == 0) {
					newWin(url);
				} else {
					alert("此链接无效");
				}
			};

			window.newWin = function(url) {
              var a = document.createElement('a');
              a.setAttribute('href', url);
              a.setAttribute('target', '_blank');
              document.body.appendChild(a);
              a.click();
              a.remove();
            };
        });
</script>
</body>
</html>
